package com.taikang.hmp.hbusiness.diabetes.measure.medicine.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.framework.common.util.IDHelper;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.service.impl.BaseServiceImpl;
import com.taikang.hmp.frame.common.tools.DateTimeUtils;
import com.taikang.hmp.hbusiness.diabetes.measure.medicine.bean.MedDictionary;
import com.taikang.hmp.hbusiness.diabetes.measure.medicine.bean.Medicine;
import com.taikang.hmp.hbusiness.diabetes.measure.medicine.bean.Medplan;
import com.taikang.hmp.hbusiness.diabetes.measure.medicine.bean.Medplandetail;
import com.taikang.hmp.hbusiness.diabetes.measure.medicine.service.IMedicineService;
import com.taikang.hmp.hbusiness.diabetes.measure.medicine.service.MedicineUtil;
import com.taikang.hmp.hbusiness.diabetes.measure.sugar.service.SugarUtil;

/**
 * 用药 author:qrp time:2015年7月29日 下午2:34:10
 */
public class MedicineServiceImpl extends BaseServiceImpl implements
		IMedicineService {

	private static Logger logger = LoggerFactory.getLogger(MedicineServiceImpl.class);
	
	
	/**
	 * 获取药品字典
	 */
	public List<Dto> getMedicineList() {
		List<MedDictionary> resultList = super.getNewDao().queryForList("medicine_space.getMedicineList");
		List<Dto> result = new ArrayList<Dto>();
		for (int i = 0; resultList!=null && i < resultList.size(); i++) {
			MedDictionary medtemp = resultList.get(i);
			Dto resultMap = new BaseDto();
			resultMap.put("medicineid", medtemp.getMedicine_id());
			resultMap.put("type", medtemp.getType());
			resultMap.put("name", medtemp.getName());
			resultMap.put("spec", medtemp.getSpec());
			resultMap.put("indication", medtemp.getIndication());
			resultMap.put("effect", medtemp.getEffect());
			
			/**
			 * 不用的大字段不传给前台
			 */
//			resultMap.put("date", "");
//			resultMap.put("supply", medtemp.getSupply());
//			resultMap.put("medname", medtemp.getMedname());
//			resultMap.put("pharmacy", medtemp.getPharmacy());
//			resultMap.put("direction", medtemp.getDirection());
			result.add(resultMap);
		}
		return result;
	}

	
	/**
	 * 保存用药计划
	 */
	public void saveMedicinePlan(Dto dto)  {
		logger.info("--保存用药计划start--");
		//
		String customer_id =dto.getAsString("customerid");
		//
		String date = dto.getAsString("date");	
		// 用药时段
		String medtimespan_cd = dto.getAsString("timespan");
		// 用量
		String value = dto.getAsString("value");
		// 药物编码
		String medicineId = dto.getAsString("medicineid");
		
		Date operate_date = new Date(); 
		//一天后日期
		Date afterDate = SugarUtil.getDateAfter(new Date(), 1);
		//先查询这个人未来一天有没有计划
		Dto dto1 = new BaseDto();
		dto1.put("customer_id", customer_id);
		dto1.put("date", DateTimeUtils.formatDate(afterDate));
		List<Dto> furlist = super.getNewDao().queryForList("medicine_space.getfurplanlist", dto1);
		List<Dto> planlist = super.getNewDao().queryForList("medicine_space.getplanlist", dto1);
		if((furlist == null || furlist.size() == 0) && planlist.size() > 0){
			//将距离今天最近的一次迁移
//			List<Dto> planlist = super.getNewDao().queryForList("medicine_space.getplanlist", dto1);
			for(Dto pl : planlist){
				String planid = pl.getAsString("plan_id");
				String new_plan_id = java.util.UUID.randomUUID().toString();
				Medplan medplan1 = new Medplan();
				medplan1.setPlan_id(new_plan_id);
				medplan1.setOperater(dto.getAsString("uid"));
				medplan1.setOperate_date(operate_date);
				medplan1.setSource_cd(dto.getAsString("requestsource"));
				medplan1.setCustomer_id(customer_id);
				medplan1.setDate(DateTimeUtils.formatDate(afterDate));
				medplan1.setMedtimespan_cd(pl.getAsString("medtimespan_cd"));
				super.getNewDao().insert("medicine_space.insert_MedicinePlan", medplan1);
				List<Dto> detailPlanList = super.getNewDao().queryForList("medicine_space.detailPlanList", planid);
				for(Dto dpl : detailPlanList){
					Medplandetail detail = new Medplandetail();
					String record_id = java.util.UUID.randomUUID().toString();
					detail.setRecord_id(record_id);
					detail.setPlan_id(new_plan_id);
					detail.setMedicine_cd(dpl.getAsString("medicine_cd"));
					detail.setMedtimespan_cd(dpl.getAsString("medtimespan_cd"));
					detail.setValue(dpl.getAsString("value"));
					detail.setOperate_date(operate_date);
					detail.setOperater(dto.getAsString("uid"));
					detail.setSource_cd(dto.getAsString("requestsource"));
					super.getNewDao().insert("medicine_space.insert_MedicinePlanDetail", detail);
				}
			}
		}
		//有，将第二天的计划进行修改
		//保存用药计划, 保证唯一：customer_id date medtimespan_cd
		String plan_id = null;
		Medplan medplan2 = new Medplan();
		medplan2.setOperater(dto.getAsString("uid"));
		medplan2.setOperate_date( operate_date );
		medplan2.setSource_cd(dto.getAsString("requestsource"));
		medplan2.setCustomer_id(customer_id);
		medplan2.setDate(DateTimeUtils.formatDate(afterDate));
		medplan2.setMedtimespan_cd(medtimespan_cd);
		Dto dto2 = new BaseDto();
		dto2.put("customerid", customer_id);
		dto2.put("timespan", medtimespan_cd);
		dto2.put("date", DateTimeUtils.formatDate(afterDate));
		dto2.put("medicineid", medicineId);
		
		Medplan existMedplan = (Medplan)super.getNewDao().queryForObject("medicine_space.getMedicinePlanByOne", dto2);
		if (existMedplan!=null) {
			plan_id = existMedplan.getPlan_id();
			super.getNewDao().update("medicine_space.update_MedicinePlan", medplan2);
		} else {
			plan_id = java.util.UUID.randomUUID().toString();
			medplan2.setPlan_id(plan_id);
			super.getNewDao().insert("medicine_space.insert_MedicinePlan", medplan2);
		}
		//保存用药明细
		Medplandetail detail = new Medplandetail();
		if (plan_id != null) {
			String record_id = java.util.UUID.randomUUID().toString();
			detail.setRecord_id(record_id);
			detail.setPlan_id(plan_id);
			detail.setMedicine_cd(medicineId);
			detail.setMedtimespan_cd(medtimespan_cd);
			detail.setValue(value);
			detail.setOperate_date( operate_date );
			detail.setOperater(dto.getAsString("uid"));
			detail.setSource_cd(dto.getAsString("requestsource"));
			//更新
			super.getNewDao().delete("medicine_space.delMedicinePlanDetail", detail);
		    super.getNewDao().insert("medicine_space.insert_MedicinePlanDetail", detail);
		}
		//删除
		if("".equals(value) || "0".equals(value)){
			super.getNewDao().delete("medicine_space.delMedicinePlan", detail.getPlan_id());
			super.getNewDao().delete("medicine_space.delMedicinePlanDetail", detail);
		}
	}
	
	
	
	/**
	 *  获取用药计划
	 */
	public List<Dto> getMedicinePlan(Dto dto) {	
		logger.info("--获取用药计划start--");
		List<Dto> results = new ArrayList<Dto>();
		//
		String customerid = dto.getAsString("customerid");
		String date =dto.getAsString("date");
		String timespan = dto.getAsString("timespan");
		Dto qdto = new BaseDto();
		qdto.put("customer_id", customerid);
		String maxdate = (String)super.getNewDao().queryForObject("medicine_space.getmaxdate",dto.getAsString("customerid"));
		//在获取用户用药记录时，记录以计划日期的最大日期获取
		int comre = 1;
		String pdate = date;
		try {
			comre = MedicineUtil.compare(maxdate, date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(comre == 0){
			pdate = maxdate;
		}else{
			Dto dto1 = new BaseDto();
			dto1.put("customerid", dto.getAsString("customerid"));
			dto1.put("date", date);
			pdate = (String)super.getNewDao().queryForObject("medicine_space.getrecordmaxdate",dto1);
		}
		String state = dto.getAsString("state");
		if(state.equals("plan")){
			qdto.put("plandate", maxdate);
			qdto.put("usedate", maxdate);
		}else{
			qdto.put("plandate", pdate);
			qdto.put("usedate", date);
		}
		qdto.put("medtimespan_cd", timespan);
		
		// 某位客人的服药情况
		List<Dto> list = super.getNewDao().queryForList("medicine_space.getMedicineInfoByCustomer", qdto);
		if (list != null && !list.isEmpty()) {
			for(Dto medInfo : list){
				Dto  result  = new BaseDto();
				result.put("planid", medInfo.getAsString("plan_id"));
				//服药日期
				String med_date = medInfo.getAsString("med_actual_date");
				if(StringUtils.isNotEmpty(med_date)){
					//格式化日期
					med_date = DateTimeUtils.formatDate(DateTimeUtils.parseDate(med_date));
				}else{
					med_date = date;
				}
				//是否服药
				String isdo = medInfo.getAsString("med_actual_value");
				if (StringUtils.isEmpty(isdo)) {
					isdo = "0";
				}
				result.put("date"      , date);
				result.put("isdo"      , isdo);
				result.put("timespan"  , medInfo.getAsString("med_plan_span"));
				result.put("value"     , medInfo.getAsString("med_plan_value"));
				result.put("medicineid", medInfo.getAsString("med_plan_medicine_id"));
				result.put("name", medInfo.getAsString("medicine_name"));
				
				results.add(result);
			}
		}
		logger.info("--获取用药计划end--");
		return results;
	}
	/**
	 * 保存用药计划
	 */
	public void saveFirstMedicinePlan(Dto dto)  {
		logger.info("--保存用药计划start--");
		//
		String customer_id =dto.getAsString("customerid");
		//
		String date = dto.getAsString("date");	
		// 用药时段
		String medtimespan_cd = dto.getAsString("timespan");
		// 用量
		String value = dto.getAsString("value");
		// 药物编码
		String medicineId = dto.getAsString("medicineid");
		
		//
		Date operate_date = new Date(); 
		Medplan medplan = new Medplan();
		medplan.setOperater(dto.getAsString("uid"));
		medplan.setOperate_date( operate_date );
		medplan.setSource_cd(dto.getAsString("requestsource"));
		medplan.setCustomer_id(customer_id);
		medplan.setDate(date);
		medplan.setMedtimespan_cd(medtimespan_cd);
		Dto dto2 = new BaseDto();
		dto2.put("customerid", customer_id);
		dto2.put("timespan", medtimespan_cd);
		dto2.put("date", date);
		dto2.put("medicineid", medicineId);
		//保存用药计划, 保证唯一：customer_id date medtimespan_cd
		String plan_id = null;
		Medplan existMedplan = (Medplan)super.getNewDao().queryForObject("medicine_space.getMedicinePlanByOne", dto2);
		if (existMedplan!=null) {
			plan_id = existMedplan.getPlan_id();
			super.getNewDao().update("medicine_space.update_MedicinePlan", medplan);
		} else {
			plan_id = java.util.UUID.randomUUID().toString();
			medplan.setPlan_id(plan_id);
			super.getNewDao().insert("medicine_space.insert_MedicinePlan", medplan);
		}
		if (plan_id != null) {
			Medplandetail detail = new Medplandetail();
			String record_id = java.util.UUID.randomUUID().toString();
			detail.setRecord_id(record_id);
			detail.setPlan_id(plan_id);
			detail.setMedicine_cd(medicineId);
			detail.setMedtimespan_cd(medtimespan_cd);
			detail.setValue(value);
			detail.setOperate_date( operate_date );
			detail.setOperater(dto.getAsString("uid"));
			detail.setSource_cd(dto.getAsString("requestsource"));
			
			super.getNewDao().delete("medicine_space.delMedicinePlanDetail", detail);
			if(!"".equals(value) && !"0".equals(value)){
			super.getNewDao().insert("medicine_space.insert_MedicinePlanDetail", detail);
			}else{
				super.getNewDao().delete("medicine_space.delMedicinePlanDestory", detail);
			}
			
		}
	}
	/**
	 *  获取用药计划最后修改时间
	 */
    public String getLastModifyDate(Dto dto) {
	   String customerid = dto.getAsString("customerid");
	   String modifyDate = (String)super.getNewDao().queryForObject("medicine_space.getLastModifyDate", customerid);
	   return modifyDate;
	}
	

	public void saveMedicineUse(Dto dto)  {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		String customer_id = dto.getAsString("customerid");
		String medtimespan_cd = dto.getAsString("timespan");// 用药时段
		String date = dto.getAsString("date");
		dto.put("date", date.substring(0, 10));
		//先删除规定日期规定时段的服药信息
		super.getNewDao().delete("medicine_space.del_exit_meduse", dto);
		//插入新的
		List<Dto> meduselist = dto.getAsList("statelist");
		for(Dto list : meduselist){
			list.put("record_id", IDHelper.genUUID());
			list.put("customer_id", customer_id);
			list.put("date", date);
			list.put("medtimespan_cd", medtimespan_cd);
			list.put("source_cd", dto.getAsString("requestsource"));
			list.put("operater", dto.getAsString("uid"));
			list.put("operate_date", new Date());
			super.getNewDao().insert("medicine_space.insert_MedicineUse", list);
		}
		
		logger.info("--保存用药记录end--");
	}

	

	@Override
	public int[] getMedicineChartList(Dto dto) {
		// TODO Auto-generated method stub
		Medicine medicine = new Medicine();
		medicine.setCustomer_id(dto.getAsString("customerid"));
		String day = dto.getAsString("day");
		int all = (Integer)super.getNewDao().queryForObject("medicine_space.getMedicinePlanCount", medicine);
//		if ("1".equals(day)) {
//			medicine.setDate(dto.getAsString("date"));
//			all = (Integer)super.getNewDao().queryForObject("medicine_space.getMedicinePlanCount", medicine);
//		} else {
//			//medicine.setDate(dto.getAsString("befdate"));
//			List<Medicine> valueList  = super.getNewDao().queryForList("medicine_space.getOneMedicinePlanCount", medicine);
//			medicine.setDate(null);
//			int value = 0;
//			if(valueList.size() > 0){
//				value = Integer.parseInt(valueList.get(0).getValue());
//			} 
////			medicine.setBef_date(dto.getAsString("befdate") + " 00:00");
////			medicine.setAft_date(dto.getAsString("aftdate") + " 23:59");
//			medicine.setBef_date(dto.getAsString("befdate"));
//			medicine.setAft_date(dto.getAsString("aftdate"));
//			List<Medicine> medicineList = super.getNewDao().queryForList("medicine_space.getMedicinePlanCounts", medicine);
//			if(medicineList.size() > 0){
//			for (int i = 0; i < medicineList.size(); i++) {
//				//用药计划中取出用药次数
//				try {
//					if(i == 0){
//						all += value*MedicineUtil.daysBetween(dto.getAsString("befdate"),medicineList.get(i).getDates());
//					}
//					else{
//						all += Integer.parseInt(medicineList.get(i-1).getValue())*MedicineUtil.daysBetween(medicineList.get(i-1).getDates(),medicineList.get(i).getDates());
//					}
//					
//						} catch (NumberFormatException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (ParseException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//			try {
//				all += Integer.parseInt(medicineList.get(medicineList.size()-1).getValue())*MedicineUtil.daysBetween(medicineList.get(medicineList.size()-1).getDates(),dto.getAsString("aftdate"));
//			} catch (NumberFormatException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			}
//		}
		//总的计划次数
		int allplan = all * Integer.parseInt(day);
		//服药的次数
		int dose = (Integer)super.getNewDao().queryForObject("medicine_space.getMedicineCount", medicine);
		int	[] counts  = {dose,allplan-dose};
		return counts;
	}

	public List<Medicine> getMedicineTableList(Dto dto) {
		List<Medicine> resultList = new ArrayList();
		Medicine medicine = new Medicine();
		Dto qdto = new BaseDto();
		qdto.put("customerid", dto.getAsString("customerid"));
		if ("1".equals(dto.getAsString("day"))) {
			qdto.put("date", dto.getAsString("date"));
		} else {
			qdto.put("befdate", dto.getAsString("befdate") + " 00:00:00");
			//qdto.put("aftdate", dto.getAsString("aftdate"));
			qdto.put("aftdate", dto.getAsString("date") + " 23:59:59");
		}
		List<Dto> times = super.getNewDao().queryForList("medicine_space.getMedicineTable", qdto);
		if (times == null) {
			return null;
		} else {
			Medicine medicineResult = new Medicine();
			for (int i = 0; i < times.size(); i++) {
				String j = times.get(i).getAsString("medtimespan_cd");
				boolean flag= false;
				if(i > 0){
					flag = times.get(i).getAsString("dates").substring(0, 10).equals(times.get(i-1).getAsString("dates").substring(0, 10));
					if(!flag){
						resultList.add(medicineResult);
						medicineResult = new Medicine();
					}
				}
				medicineResult.setDates(times.get(i).getAsString("dates").substring(0, 10));
					if ("0".equals(j)) {
						if (medicineResult.getBreakfast_pre() == null) {
							medicineResult.setBreakfast_pre(times.get(i).getAsString("value"));
						}else{
							String pre = medicineResult.getBreakfast_pre();
							if(pre.equals("1")){
								medicineResult.setBreakfast_pre(times.get(i).getAsString("value"));
							}
						}
					} else if ("1".equals(j)) {
						if (medicineResult.getBreakfast_aft() == null) {
							medicineResult.setBreakfast_aft(times.get(i).getAsString("value"));
						}else{
							String pre = medicineResult.getBreakfast_aft();
							if(pre.equals("1")){
								medicineResult.setBreakfast_aft(times.get(i).getAsString("value"));
							}
						}
					} else if ("2".equals(j)) {
						if (medicineResult.getLunch_pre() == null) {
							medicineResult.setLunch_pre(times.get(i).getAsString("value"));
						}else{
							String pre = medicineResult.getLunch_pre();
							if(pre.equals("1")){
								medicineResult.setLunch_pre(times.get(i).getAsString("value"));
							}
						}
					} else if ("3".equals(j)) {
						if (medicineResult.getLunch_aft() == null) {
							medicineResult.setLunch_aft(times.get(i).getAsString("value"));
						}else{
							String pre = medicineResult.getLunch_aft();
							if(pre.equals("1")){
								medicineResult.setLunch_aft(times.get(i).getAsString("value"));
							}
						}
					} else if ("4".equals(j)){
						if (medicineResult.getDinner_pre() == null) {
							medicineResult.setDinner_pre(times.get(i).getAsString("value"));
						}else{
							String pre = medicineResult.getDinner_pre();
							if(pre.equals("1")){
								medicineResult.setDinner_pre(times.get(i).getAsString("value"));
							}
						}
					} else if ("5".equals(j)){
						if (medicineResult.getDinner_aft() == null) {
							medicineResult.setDinner_aft(times.get(i).getAsString("value"));
						}else{
							String pre = medicineResult.getDinner_aft();
							if(pre.equals("1")){
								medicineResult.setDinner_aft(times.get(i).getAsString("value"));
							}
						}
					} else if ("6".equals(j)) {
						if (medicineResult.getSleep_pre() == null) {
							medicineResult.setSleep_pre(times.get(i).getAsString("value"));
						}else{
							String pre = medicineResult.getSleep_pre();
							if(pre.equals("1")){
								medicineResult.setSleep_pre(times.get(i).getAsString("value"));
							}
						}
					}
					if(i == times.size()-1){
							resultList.add(medicineResult);
					}
			}
		}
		return resultList;
	}
	
	
}
